<?php
declare (strict_types = 1);

namespace app\frontend\controller;

use think\facade\Db;
use think\facade\Validate;

class SubPlan extends Base
{
    // 子计划页面
    public function index()
    {
        $pid = (int)input('get.pid', '', 'strip_tags');

        return view('', ['pid' => $pid]);
    }

    // 计划列表数据接口
    public function list()
    {
        $pid = request()->param('pid');
        $page = request()->param('page');
        $limit = request()->param('limit');
        $status = request()->param('status');
        $name = request()->param('name');

        if ($status == 'all') {
            $status = [1, 2, 3];
        } else {
            $status = [$status];
        }

        $planList = \app\frontend\model\Plan::field('id,project_id,name,start_time,end_time,status,priority')
            ->where([
                ['name', 'like', '%'.$name.'%'],
                ['status', 'in', $status],
                ['pid', '=', $pid],
            ])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'var_page' => 'page',
                'page' => $page,
                'query' => [
                    'name' => $name,
                    'status' => $status
                ]
            ]);

        $planListData = $planList->toArray()['data'];
        foreach ($planListData as &$plan) {
            $plan['start_time'] = date('Y-m-d H:i:s', $plan['start_time']);
            $plan['end_time'] = date('Y-m-d H:i:s', $plan['end_time']);
        }

        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $planList->total(),
            'data' => $planListData
        ];

        return json($data);
    }

    // 子计划添加页
    public function add()
    {
        $pid = (int)input('get.pid', '', 'strip_tags');

        return view('', [
            'pid' => $pid
        ]);
    }

    // 计划添加页面保存接口
    public function save()
    {
        $params['name'] = trim(input('post.name', '', 'strip_tags'));
        $params['pid'] = trim(input('post.pid', '', 'strip_tags'));
        $params['project_id'] = trim(input('post.project', '', 'strip_tags'));
        $params['desc'] = trim(input('post.desc', '', 'strip_tags'));
        $params['startTime'] = strtotime(trim(input('post.startTime', '', 'strip_tags')));
        $params['endTime'] = strtotime(trim(input('post.endTime', '', 'strip_tags')));
        $params['estimateTime'] = trim(input('post.estimateTime', '', 'strip_tags'));
        $params['priority'] = trim(input('post.priority', '', 'strip_tags'));

        $validate = Validate::rule([
            'name|名称' => 'require|max:20',
            'startTime|开始时间' => 'require',
            'endTime|结束时间' => 'require',
            'desc|详情描述' => 'max:255',
            'estimateTime|估算时间' => 'require|max:20',
            'priority|优先级' => 'require'
        ]);
        if (!$validate->check($params)) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        // 启动事务
        Db::startTrans();
        try {
            // 查询父计划
            $pPlan = \app\frontend\model\Plan::find($params['pid']);

            $userInfo = session('userInfo');
            \app\frontend\model\Plan::create([
                'name' => $params['name'],
                'project_id' => $pPlan->project_id,
                'desc' => $params['desc'],
                'status' => 1,
                'start_time' => $params['startTime'],
                'end_time' => $params['endTime'],
                'user_id' => $pPlan->user_id,
                'estimate_time' => $params['estimateTime'],
                'priority' => $params['priority'],
                'pid' => $params['pid']
            ]);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json([
                'code' => 2,
                'msg' => $e->getMessage()
            ]);
        }

        return json([
            'code' => 0,
            'msg' => '保存成功'
        ]);
    }

    // 计划查看编辑页
    public function edit()
    {
        // 任务信息
        $id = (int)input('get.id', '', 'strip_tags');
        $plan = \app\frontend\model\Plan::field('id,name,desc,start_time,end_time,status,finish_time,estimate_time,priority')
            ->find($id)->toArray();

        return view('', [
            'plan' => $plan
        ]);
    }

    // 编辑页面保存接口
    public function update()
    {
        // 计划信息
        $params['id'] = (int)trim(input('post.id', '', 'strip_tags'));
        $params['name'] =  trim(input('post.name', '', 'strip_tags'));
        $params['desc'] = trim(input('post.desc', '', 'strip_tags'));
        $params['startTime'] = strtotime(trim(input('post.startTime', '', 'strip_tags')));
        $params['endTime'] = strtotime(trim(input('post.endTime', '', 'strip_tags')));
        $params['estimateTime'] = trim(input('post.estimateTime', '', 'strip_tags'));
        $params['priority'] = trim(input('post.priority', '', 'strip_tags'));

        // 格式验证
        $validate = Validate::rule([
            'id|id' => 'require|integer',
            'name|名称' => 'require|max:20',
            'startTime|开始时间' => 'require',
            'endTime|结束时间' => 'require',
            'desc|详情描述' => 'max:255',
            'estimateTime|估算时间' => 'require|max:20',
            'priority|优先级' => 'require'
        ]);
        if (!$validate->check($params)) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        // 优先级参数设置
        switch ($params['priority']) {
            case '低':
                $params['priority'] = 1;
                break;
            case '中':
                $params['priority'] = 2;
                break;
            case '高':
                $params['priority'] = 3;
                break;
            default:
                return json([
                    'code' => 2,
                    'msg' => '优先级参数错误'
                ]);
        }

        \app\frontend\model\Plan::update([
            'id' => $params['id'],
            'name' => $params['name'],
            'desc' => $params['desc'],
            'start_time' => $params['startTime'],
            'end_time' => $params['endTime'],
            'estimate_time' => $params['estimateTime'],
            'priority' => $params['priority']
        ]);

        return json([
            'code' => 0,
            'msg' => '修改成功'
        ]);
    }
}
